package com.dimples.wxpush.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.dimples.wxpush.constant.ConfigConstant;
import com.dimples.wxpush.model.bo.WeatherHourlyBO;
import com.dimples.wxpush.model.bo.WeatherNowBO;
import com.dimples.wxpush.model.bo.WeatherThreeDayBO;
import com.dimples.wxpush.service.TianqiService;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取城市的天气并处理
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/11/15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TianqiServiceImpl implements TianqiService {

    private final String weatherUrl = "https://devapi.qweather.com/v7/weather";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ConfigConstant configConstant;

    @Override
    public WeatherNowBO getNowWeather() {
        String result = HttpUtil.get(weatherUrl + "/now?location=" + configConstant.getCity() + "&key=" + configConstant.getWeatherAppSecret());
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (StrUtil.equals(jsonObject.getString("code"), "200")) {
            return JSONUtil.toBean(jsonObject.getString("now"), WeatherNowBO.class);
        } else {
            throw new RuntimeException("获取实时小时天气失败");
        }
    }

    @Override
    public Map<String, String> getTheNextThreeDaysWeather() {
        Map<String, String> map;
        String result = HttpUtil.get(weatherUrl + "/3d?location=" + configConstant.getCity() + "&key=" + configConstant.getWeatherAppSecret());
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!StrUtil.equals(jsonObject.getString("code"), "200")) {
            logger.error("获取三天天气失败,检查配置文件");
            throw new RuntimeException("获取三天天气失败,检查配置文件");
        }

        logger.info(result);
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        LocalDate now = LocalDate.now(zoneId);
        //封装今天，明天，后天的时间
        Map<Integer, String> daySet = new HashMap<>();
        daySet.put(now.getDayOfMonth(), "今");
        daySet.put(now.plusDays(1L).getDayOfMonth(), "明");
        daySet.put(now.plusDays(2L).getDayOfMonth(), "后");
        //过滤，提取结果
        if (jsonObject.containsKey("error")) {
            logger.error(jsonObject.get("error").toString());
            throw new IllegalArgumentException(jsonObject.get("error").toString());
        }
        map = jsonObject.getJSONArray("daily").stream()
                .peek(o -> {
                    String date = getStringFromJson(o, "fxDate").substring(8);
                    ((JSONObject) o).put("fxDate", date);
                })
                .filter(o -> daySet.containsKey(getIntegerFromJson(o, "fxDate")))
                .collect(Collectors.toMap(
                        key -> daySet.get(getIntegerFromJson(key, "fxDate")),
                        value -> getStringFromJson(value, "textDay")));
        return map;
    }

    @Override
    public List<WeatherThreeDayBO> getTheNextThreeDaysWeatherList() {
        String response = HttpUtil.get(weatherUrl + "/3d?location=" + configConstant.getCity() + "&key=" + configConstant.getWeatherAppSecret());
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (StrUtil.equals(jsonObject.getString("code"), "200")) {
            return JSONUtil.toList(jsonObject.getString("daily"), WeatherThreeDayBO.class);
        } else {
            throw new RuntimeException("获取24小时天气失败");
        }
    }

    @Override
    public List<WeatherHourlyBO> get24hWeatherList() {
        String response24h = HttpUtil.get(weatherUrl + "/24h?location=" + configConstant.getCity() + "&key=" + configConstant.getWeatherAppSecret());
        JSONObject jsonObject = JSONObject.parseObject(response24h);
        if (StrUtil.equals(jsonObject.getString("code"), "200")) {
            return JSONUtil.toList(jsonObject.getString("hourly"), WeatherHourlyBO.class);
        } else {
            throw new RuntimeException("获取24小时天气失败");
        }
    }

    private String getStringFromJson(Object obj, String key) {
        if (obj instanceof JSONObject) {
            return ((JSONObject) obj).getString(key);
        }
        return null;
    }

    private Integer getIntegerFromJson(Object obj, @SuppressWarnings("SameParameterValue") String key) {
        if (obj instanceof JSONObject) {
            return Integer.valueOf(((JSONObject) obj).getString(key));
        }
        return null;
    }
}
